/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elaborate.tag_analysis.client.actions;

import elaborate.tag_analysis.client.actions.ui.MultipleFileSelectionDialog;
import elaborate.tag_analysis.client.actions.ui.multiplefileselector.MultipleFileSelectionConfEntry;
import elaborate.tag_analysis.model.TURRelation;
import elaborate.tag_analysis.model.Tag;
import elaborate.tag_analysis.restws.client.TURRelationDao;
import elaborate.tag_analysis.restws.client.TagDao;
import elaborate.task.Task;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author lendle
 */
public class GenerateCharacteristicVectorActionHandler extends BaseActionHandler {
    @Override
    protected void asyncHandleAction(ActionEvent event) {
        try {
            List<MultipleFileSelectionConfEntry> entries=new ArrayList<MultipleFileSelectionConfEntry>();
            
            MultipleFileSelectionConfEntry vectorFileEntry=new MultipleFileSelectionConfEntry();
            vectorFileEntry.setId("list");
            vectorFileEntry.setDisplayName("Select Resource List File");
            entries.add(vectorFileEntry);
            
            MultipleFileSelectionConfEntry csvFileEntry=new MultipleFileSelectionConfEntry();
            csvFileEntry.setId("vector");
            csvFileEntry.setDisplayName("Select Output Vector File");
            csvFileEntry.setSave(true);
            entries.add(csvFileEntry);
            
            final MultipleFileSelectionDialog dlg=new MultipleFileSelectionDialog((Frame)context.getMainFrame(), true);
            dlg.getFileSelector().setMultipleFileSelectionConfEntries(entries);
            dlg.setLocationRelativeTo(context.getMainFrame());
            dlg.setVisible(true);
            
            if (dlg.isOk()) {
                context.executeTask(new Task() {

                    @Override
                    public Object run() throws Exception {
                        TURRelationDao turDao = context.getActiveApplication().getDaoFactory().createTURRelationDao();
                        TagDao tagDao = context.getActiveApplication().getDaoFactory().createTagDao();
                        List<String> resources = new ArrayList<String>();
                        
                        BufferedReader input=null;
                        PrintWriter output = null;
                        try {
                            //load resource list from file
                            input=new BufferedReader(new InputStreamReader(new FileInputStream(dlg.getFileSelector().getSelectedFile("list")), "utf-8"));
                            String str=input.readLine();
                            while(str!=null){
                                resources.add(str);
                                str=input.readLine();
                            }
                            //////////////////////////////
                            output = new PrintWriter(new OutputStreamWriter(new FileOutputStream(dlg.getFileSelector().getSelectedFile("vector")), "utf-8"));
                            List<Tag> tags = tagDao.findAll(context.getActiveApplication().getApplicationId());
                            int count = 0;
                            for (Tag tag : tags) {
                                List<TURRelation> turs4Tag = turDao.findByTagId(context.getActiveApplication().getApplicationId(), tag.getId());
                                if (turs4Tag == null || turs4Tag.isEmpty()) {
                                    continue;
                                }
                                Map<String, String> occurrenceMap = new HashMap<String, String>();
                                for (TURRelation tur : turs4Tag) {
                                    occurrenceMap.put(tur.getResourceId(), "");
                                }
                                StringBuffer buffer = new StringBuffer();
                                buffer.append("\"").append(tag.getId()).append("\" ");
                                for (String resource : resources) {
                                    if (occurrenceMap.containsKey(resource)) {
                                        buffer.append("1");
                                    } else {
                                        buffer.append("0");
                                    }
                                }
                                output.println(buffer.toString());
                                System.out.println("" + (++count) + "/" + tags.size());
                            }
                        } finally {
                            if (output != null) {
                                output.close();
                            }
                            if(input!=null){
                                input.close();
                            }
                        }
                        return null;
                    }
                });

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
